# -*- coding: utf-8 -*-

import web
from core import Config, Server, rTorrent_config
from templatetags import humanize, global_statistic, crutch
import re, os.path
from xmlrpclib import Fault, ProtocolError

render = web.template.render('templates/', base='base')
config = Config("wrTorrent.py.cfg")
server = Server(config)
server.connect()

def setheader():
   web.header("Content-Type","text/html; charset=utf-8")
#app.add_processor(loadhook(setheader))
#web.loadhooks['setheader'] = setheader

def fault(msg, name=None):
    errors = []
    if not name is None:
        errors.append(name)
    errors.append("XML-RPC Error %d: %s" % (msg.faultCode, msg.faultString))
    if msg.faultCode == -501:
        errors.append("Try using multicall only for hash in settings.")
    return errors

class index:
    def GET(self):
        return web.seeother("/list/")
        
class list:
    def GET(self, mode = "default"):
        try:
            download_list = server.list(mode)
        except Fault, msg:
            return render.error(fault(msg, "Getting torrent list error"))
        except Exception, msg:
            return render.error([msg])
        return render.index(download_list)
        
class start:
    def GET(self):
        i = web.input()
        try:
            server.open(i.hash)
            server.start(i.hash)
        except:
            return web.seeother("/ooops/")
        return web.seeother("/list/")
        
class stop:
    def GET(self):
        i = web.input()
        try:
            server.stop(i.hash)
        except:
            return web.seeother("/ooops/")
        return web.seeother("/list/")
        
class delete:
    def GET(self):
        i = web.input()
        try:
            server.erase(i.hash)
        except:
            return web.seeother("/ooops/")
        return web.seeother("/list/")
        
class action:
    def POST(self):
        action = None
        torrents = []
        priorities = []
        i = web.input(ufile={})
        for name in i:
            if "start" in name:
                action = 0
            elif "stop" in name:
                action = 1
            elif "add" in name:
                action = 2
            elif "delete" in name:
                action = 3
            elif "set_priority" in name:
                action = 4
            if "t-" in name:
                torrents.append(name)
            if "p-" in name:
                priorities.append((name, i[name]))
        if action == 0:
            for torrent in torrents:
                try:
                    server.open(i[torrent])
                except:
                    return web.seeother("/ooops/")
        elif action == 1:
            for torrent in torrents:
                try:
                    server.close(i[torrent])
                except:
                    return web.seeother("/ooops/")
        elif action == 2:
            print i.ufile.filename
            if i.url != "":
                if re.match(r"^[http://|ftp://].*\..*", i.url):
                    try:
                        server.add(i.url)
                    except:
                        return web.seeother("/ooops/")
            elif i.ufile.filename != "":
                f = open("%s%s%s" %(
                    os.path.dirname(os.path.abspath(__file__)),
                    "/static/torrents/", i.ufile.filename), "wb")
                f.write(i.ufile.value)
                f.close()
                try:
                    server.add("%s%s%s" % (config.domain,
                        "/static/torrents/", i.ufile.filename))
                except:
                    return web.seeother("/ooops/")
        elif action == 3:
            for torrent in torrents:
                try:
                    server.erase(i[torrent])
                except:
                     return web.seeother("/ooops/")
        elif action == 4:
            for torrent in priorities:
                try:
                    server.set_priority(torrent[0][2:], torrent[1])
                except:
                    return web.seeother("/ooops/")
        return web.seeother("/list/")
        
class settings:
    def GET(self):
        try:
            rtorrent_config = rTorrent_config(server.rt)
            help = rtorrent_config.parse_help()
            rtorrent = rtorrent_config.listMethods(server.rt.system.listMethods(), help)
        except:
            rtorrent = None
        return render.settings(config, rtorrent)
    def POST(self):
        i = web.input()
        config.protocol = i.protocol
        config.url = i.url
        config.domain = i.domain
        config.multicall = int(i.multicall)
        config.save()
        try:
            server.connect()
        except:
            return web.seeother("/ooops/")
        return web.seeother("/settings/")
        
class detail:
    def GET(self, hash):
        try:
            torrent = server.get_torrent(hash)
        except Fault, msg:
            return render.error(fault(msg, "Getting torrent info error"))
        try:
            files = server.files(hash, torrent.chunk_size)
        except Fault, msg:
            return render.error(fault(msg, "Getting torrent files error"))
        return render.detail(torrent, files)
        
class detail_actions:
    def POST(self, hash):
        i = web.input()
        if "set_priority" in i.keys():
            try:
                server.set_priority(hash, i.priority)
            except:
                return web.seeother("/ooops/")
        if "set_files_priority" in i.keys():
            for name in i:
                if "p-" in name:
                    try:
                        server.set_files_priority(hash, name[2:], i[name])
                    except:
                        return web.seeother("/ooops/")
        return web.seeother("/detail/%s" % hash)
        
class ooops:
    def GET(self):
        return render.error()
        
class set_rtorrent:
    def POST(self):
        errors = []
        i = web.input()
        for name in i:
            if "set_" in name:
                if i[name] != "":
                    try:
                        value = int(i[name])
                        try:
                            eval("server.rt.%s(%d)" % (name, value))
                        except Error, msg:
                            errors.append("%s in %s" % (msg, name))
                    except:
                        value = i[name]
                        try:
                            eval("server.rt.%s(\"%s\")" % (name, value))
                        except Error, msg:
                            errors.append("%s in %s" % (msg, name))
        if len(errors) != 0:
            return render.error(errors)
        else:
            return web.seeother("/settings/")
